package open.panxiong.shared.http.controller

import android.content.Context
import fi.iki.elonen.NanoHTTPD.IHTTPSession
import fi.iki.elonen.NanoHTTPD.Response
import fi.iki.elonen.NanoHTTPD.getMimeTypeForFile
import fi.iki.elonen.NanoHTTPD.newFixedLengthResponse
import open.panxiong.shared.http.config.ConstConfig
import open.panxiong.shared.http.model.NanohttpdResponse
import java.io.File
import java.io.FileInputStream

/**
 * 因为 NanoHTTPD 不支持路径参数，所有需要单独为下载提供一个处理函数
 */
object DownloadController {

    // 给共享文件夹增加下载功能
    fun download(context: Context, session: IHTTPSession): Response? {
        val filename = session.uri.substring(ConstConfig.API_PREFIX_DOWNLOAD.length)
        try {
            val path =
                ConstConfig.getSharedFileDirectory(context).absolutePath + File.separator + filename
            val file = File(path)
            if (!file.exists()) {
                return NanohttpdResponse().to404()
            }
            val stream = FileInputStream(file)
            val response = newFixedLengthResponse(
                Response.Status.OK, getMimeTypeForFile(file.name), stream, file.length()
            )
            return response
        } catch (e: Exception) {
            return NanohttpdResponse().to500(e.message.toString())
        }
    }

}